package com.darchrow.springcloud.lb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author mdl
 * @version 1.0
 * @date 2020/8/26 16:02
 */
@Component
@Slf4j
public class MyLb implements ILoadBalancer {

    private AtomicInteger cyclicCounter = new AtomicInteger(0);

    public final int getIncrementIndex() {
        int current;
        int next;
        do {
            current = this.cyclicCounter.get();
            next = current >= 2147483647 ? 0 : current + 1;
            // CAS设置成功了就获取到了下标，防止高并发场景
        } while (!this.cyclicCounter.compareAndSet(current, next));
        log.info("****这是第几次访问，次数: " + next);
        return next;
    }


    @Override
    public ServiceInstance getInstance(List<ServiceInstance> instances) {
        int index = getIncrementIndex() % instances.size();
        return instances.get(index);
    }
}
